import { createSlice } from "@reduxjs/toolkit";
import { loginApi,getUserInfoApi } from "@/apis/user";
import {setToken as _setToken,getToken,removeToken} from "@/utils"

const userStore = createSlice({
  name: "user",
  initialState: {
    token: getToken() || "",
    userInfo:{}
  },
  reducers: {
    setToken(state, action) {
      state.token = action.payload;
      _setToken(action.payload)
    },
  
    setUserInfo(state, action) {
      state.userInfo = action.payload;
    },
    clearUserInfo(state){
      state.token = ""
      state.userInfo ={}
      removeToken()
    }
  },
});
const { setToken,setUserInfo,clearUserInfo } = userStore.actions;
// 异步获取token
const fetchLogin = (loginForm) => {
  return async (dispatch) => {
    const {data:{data:{token}}} = await loginApi(loginForm);
    dispatch(setToken(token));
  };
};

//获取个人信息
const fetchUserInfo = () => {
  return async (dispatch) => {
    const res = await getUserInfoApi();
    dispatch(setUserInfo(res.data.data));
  };
};


const userReducer = userStore.reducer;

export { fetchLogin, setToken,fetchUserInfo,clearUserInfo };

export default userReducer;
